package Sort;

public class SelectSort {
    /**
     * 选择排序
     */

    public static void selectSort2(int[] arr){
        int left=0;
        int right=arr.length-1;
        while (left<right){
            int minIndex=left;
            int maxIndex=left;
            for (int j = left+1; j <=right; j++) {
                if(arr[j]>arr[maxIndex]){
                    maxIndex=j;
                }
                if ((arr[j]<arr[minIndex])){
                    minIndex=j;
                }
            }
            swap(arr,left,minIndex);
            if(maxIndex==left){
                maxIndex=minIndex;
            }
            swap(arr,right,maxIndex);
            left++;
            right--;
        }
    }
    public static void selectSort(int[] arr){
        for (int i = 0; i <arr.length; i++) {
            int minIndex=i;
            for (int j = i+1; j <arr.length; j++) {
                if(arr[j]<arr[minIndex]){
                    minIndex=j;
                }
            }
            swap(arr,i,minIndex);
        }
    }
    public static void swap(int[] arr,int i,int j){
        int tem=arr[i];
        arr[i]=arr[j];
        arr[j]=tem;
    }
    public static void main(String[] args) {
        int[] array={9,8,7,6,5,4,3,2,1};
        selectSort2(array);
        for (int i = 0; i <array.length; i++) {
            System.out.print(array[i]+" ");
        }
    }
}
